local function parse(line, beg, fin)
    local seq = {}
    local slen = 0
    local i = beg
    while i < fin do
        local ch = string.sub(line, i, i)
        
        if not ch then
            print("Unexcepted EOF: ", string.sub(line, i - slen, i - 1))
            return nil
        end

        if ch == " " then
            if slen > 0 then
                seq[#seq + 1] = string.sub(line, i - slen, i - 1)
                slen = 0
            end
        elseif ch == "(" then
            if slen > 0 then
                seq[#seq + 1] = string.sub(line, i - slen, i - 1)
                slen = 0
            end
            i = i + 1
            local e = i
            while e < fin and string.sub(line, e, e) ~= ")" do
                e = e + 1
            end

            seq[#seq + 1] = parse(line, i, e)
            i = e + 1
        else
            slen = slen + 1
        end

        i = i + 1
    end

    if slen > 0 then
        seq[#seq + 1] = string.sub(line, fin - slen, fin - 1)
    end

    return seq
end

local function do_seq(seq)
    if not seq then
        return false
    end

    if type(seq) == "string" then
        return turtle[seq]()
    end

    local cf = seq[#seq]

    if cf == "E" then
        local len = #seq - 1
        while true do
            for i=1, len do
                if not do_seq(seq[i]) then
                    return false
                end
            end
        end
    else
        local times = tonumber(cf)
        local len = #seq
        if times then
            len = len - 1
        else
            times = 1
        end

        for n=1, times do
            for i=1, len do
                do_seq(seq[i])
            end
        end
    end
end

local histroy = {}


while true do
    write("tact> ")
    local line = read(nil, histroy)
    if #line == 0 then
        goto continue
    elseif line == "Q" then
        break
    end

    histroy[#histroy + 1] = line
	
    local seq = parse(line, 1, #line + 1)
    -- print(textutils.serialise(seq))
    do_seq(seq)

    ::continue::
end
